<template>
  <div><h2>跳转中，请稍后...</h2></div>
</template>
<script>
import db from '@/utils/localstorage'
import { randomNum } from '@/utils'
import axios from 'axios'

export default {
  name: 'ssoLogin',
  data () {
    return {
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      randomId: randomNum(24, 16),
      imageCode: '',
      thirdPartTokenInfo: '',
      page: {
        width: window.screen.width * 0.5,
        height: window.screen.height * 0.5
      }
    }
  },
  mounted () {
    db.clear()
    // this.handleLogin()
    this.loginAction()
  },
  destroyed () {
    window.removeEventListener('message', this.resolveSocialLogin)
  },
  methods: {
    getCodeImage () {
      axios({
        method: 'GET',
        url: `${this.codeUrl}?key=${this.randomId}`,
        responseType: 'arraybuffer'
      })
        .then((res) => {
          return (
            'data:image/png;base64,' +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ''
              )
            )
          )
        })
        .then((res) => {
          this.imageCode = res
        })
        .catch((e) => {
          if (e.toString().indexOf('429') !== -1) {
            this.$message({
              message: this.$t('tips.tooManyRequest'),
              type: 'error'
            })
          } else {
            this.$message({
              message: this.$t('tips.getCodeImageFailed'),
              type: 'error'
            })
          }
        })
    },
    handleTabClick (tab, event) {
      this.tabActiveName = tab.name
    },
    // resolveLogo(logo) {
    //   return require(`@/assets/logo/${logo}`)
    // },
    handleLogin () {
      const token = this.getUrlKey('token')
      console.log(token)
      if (token == null) {
        alert('非法请求!')
      } else {
        this.$util.http.post('/sso/getThirdPartyUserInfo?token=' + token).then((r) => {
          const data = r.data
          this.thirdPartTokenInfo = JSON.stringify(data)
          // console.log(this.thirdPartTokenInfo)
          if (data.userId == null) { // 检查username是否为空
            alert('请检查相关参数!')
          } else {
            this.loginAction()
          }
        })
      }
    },
    loginAction () {
      localStorage.setItem('rememberme', 0)
      this.$util.http.post('/api/system/login', { // 调用登录
        username: 'admin',
        password: this.$util.encryptPassword
          ? this.$util.encryptPassword('ctsi@111')
          : 'ctsi@111',
        rememberme: localStorage['rememberme'],
        tenantAccount: 'default'
        // key: this.randomId
      }).then((r) => {
        console.log(r.data)
        localStorage.setItem('token', r.data.token)
        this.$Message.success({
          content: '登录成功！',
          onClose: () => {
            this.$router.replace('/ImportExcel')
          }
        })
        // const data = r.data
        // this.$store.commit('account/setThirdPartyToken', this.thirdPartTokenInfo)
        // this.saveLoginData(data)
        // this.getUserDetailInfo()
        // this.loginSuccessCallback()
      }).catch((error) => {
        console.error(error)
        // eslint-disable-next-line no-undef
        that.loading = false
        // eslint-disable-next-line no-undef
        // that.getCodeImage()
      })
    },
    getUrlKey (name) {
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
            location.href
          ) || [, ''])[1].replace(/\+/g, '%20')
        ) || null
      )
    },
    saveLoginData (data) {
      this.$store.commit('account/setAccessToken', data.access_token)
      this.$store.commit('account/setRefreshToken', data.refresh_token)
      const current = new Date()
      const expireTime = current.setTime(
        current.getTime() + 1000 * data.expires_in
      )
      this.$store.commit('account/setExpireTime', expireTime)
    },
    getUserDetailInfo () {
      this.$get('auth/user')
        .then((r) => {
          this.$store.commit('account/setUser', r.data.principal)
          this.$message({
            message: this.$t('tips.loginSuccess'),
            type: 'success'
          })
          this.loading = false
          this.$router.push('/demp/alertcenter/index')
        })
        .catch((error) => {
          this.$message({
            message: this.$t('tips.loginFail'),
            type: 'error'
          })
          console.error(error)
          this.loading = false
        })
    },
    loginSuccessCallback () {
      this.$get('system/user/success').catch((e) => {
        console.log(e)
      })
    }
  }
}
</script>
